package chatroom;

import chatroom.bean.Message;
import com.alibaba.fastjson.JSON;
import constutil.Constants;
import constutil.MyMsgUtil;
import constutil.Result;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Gong
 * @Description 收消息
 * @dATE 2022/4/18 16:37
 **/
@WebServlet("/receiveMsgServlet")  //不能重名
public class ReceiveMsgServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        //登录后是有用户信息
        String fromName = (String)req.getSession().getAttribute(Constants.SESSION_USER_ID);//发送者
        String toName = req.getParameter("toName");//接受者
        String msgContent = req.getParameter("message");//消息内容
        //toName：账号，message:消息
        Message myMessage = new Message(fromName,toName,msgContent,new Date());
        System.out.println(myMessage);

        String mysSessionKey = MyMsgUtil.getMySessionKey(fromName,toName);
        ServletContext sc = this.getServletContext();
        Object chatSession = sc.getAttribute(mysSessionKey);
        if(null == chatSession){
            List messageList = new ArrayList();
            messageList.add(myMessage);
            sc.setAttribute(mysSessionKey,messageList);//首次初始化消息集合
        }else{
           List tempMessageList = (List) chatSession;
           tempMessageList.add(myMessage);
           sc.setAttribute(mysSessionKey,tempMessageList);//追加消息
        }
        //返回信息，需要定义一个结果集
        Result res = new Result(200,"success");
        //将JSON对象转化为字符串
        String objStr = JSON.toJSONString(res);
        resp.getWriter().write(objStr);
        resp.getWriter().flush();
        resp.getWriter().close();
    }
}
